using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Engine.Business.Abstract;

namespace Engine.Factory
{
    public class CollectionEntityScanner:Engine.Business.Interfaces.IScanner
    {
        #region MEMBERS
        private DataRow[] Rows = null;
        private Engine.Business.Interfaces.IHunterLog Logger = null;
        #endregion

        public CollectionEntityScanner(DataRow[] r, Engine.Business.Interfaces.IHunterLog log)
        {
            Rows = r;
            Logger = log;
        }

        public IEnumerable<CollectionItem> Scan()
        {
            Engine.Business.Abstract.CollectionItem it;
            foreach(DataSchema.CollectionSchema.ItemRow dr in Rows)
            {
                it = CollectionFactory.CreateNewCollectionItem();
                it.Name = dr.Name;
                it.CRC32 = dr.CRC32;
                it.Size = dr.Size;
                it.Description = dr.Shot;
                it.Owner = dr;
                DataSchema.CollectionSchema.ShotRow sr = DataSchema.CollectionSchema.GetItemShot(dr);
                
                if(sr.IsLinkedToNull() || sr.LinkedTo == "")
                    it.LinkedPath = "";
                else
                    it.LinkedPath = sr.LinkedTo;

                Engine.Business.Abstract.NotifyOwner notify_handler = delegate(object sender, CSV.ItemState itemstate)
                {
                    Engine.Business.Abstract.CollectionItem item = (Engine.Business.Abstract.CollectionItem)sender;
                    DataSchema.CollectionSchema.ItemRow itemrow = (DataSchema.CollectionSchema.ItemRow) item.Owner;

                    if (itemstate == Engine.CSV.ItemState.New || itemstate == Engine.CSV.ItemState.Valid)
                    {
                        ((DataSchema.CollectionSchema)itemrow.Table.DataSet).NewItemWasHunted(itemrow);
                    }

                    Logger.Log(item, itemstate);
                };

                it.Notify = notify_handler;

                yield return it;
            }
        }

        public int Count
        {
            get { return Rows.Length; }
        }
    }
}
